package com.vanzo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import com.vanzo.Tpplication;
import com.vanzo.instruction.AT;
import com.vanzo.instruction.Instruction;
import com.vanzo.util.LogUtil;

/**
 * Created by tisen on 2018/2/23.
 */

public class InstructionService extends Service {

    public static final String TAG = "InstructionService";
    private Messenger client;


    class InComingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            LogUtil.put(TAG, "msg = " + msg.toString(), LogUtil.WARN);
            client = msg.replyTo;
            String at = AT.DMO_PTT+":"+msg.what;
            instruction.sendInstruction(at);
        }
    }

    final Messenger messenger = new Messenger(new InComingHandler());

    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.put(this, "onBind", LogUtil.WARN);
        return messenger.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtil.put(this, "onUnbind", LogUtil.WARN);
        return super.onUnbind(intent);
    }

    private Instruction instruction;

    @Override
    public void onCreate() {
        super.onCreate();
        instruction = ((Tpplication) getApplication()).getInstruction();
//        instruction.setListener(resultListener);
        LogUtil.put(this, "onCreate", LogUtil.WARN);
    }

    private Instruction.OnResultListener resultListener = new Instruction.OnResultListener() {
        @Override
        public void onResult(String result) {
            if (client != null) {
                Message replyMsg = null;
                replyMsg = Message.obtain(null, 0);
                replyMsg.obj = result;
                try {
                    client.send(replyMsg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.put(this, "onStartCommand", LogUtil.WARN);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.put(this, "onDestroy", LogUtil.WARN);
    }
}
